package com.example.lprxjava;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import android.util.Log;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Author by lp,on 2021/8/17/017,16:00.
 * 手写RxLifCycle
 */
public class RxLifecycle<T> implements LifecycleObserver, ObservableTransformer<T,T> {
    private static final String TAG = "RxLifecycle";

    final CompositeDisposable compositeDisposable = new CompositeDisposable();

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy() {
        Log.i(TAG, "RxLifecycle onDestroy: ");
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
    }

    @Override
    public ObservableSource apply(Observable upstream) {
        //doOnSubscribe 在onSubscribe调用之前调用
        return upstream.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                compositeDisposable.add(disposable);
            }
        });
    }

    public static <T>RxLifecycle<T> bindRxLifecycle(LifecycleOwner lifecycleOwner) {

        RxLifecycle<T> lifecycle = new RxLifecycle();
        lifecycleOwner.getLifecycle().addObserver(lifecycle);
        return lifecycle;
    }
}
